<?
/**
 * This file is part of XNAT light.
 *
 * XNAT light is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XNAT light is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XNAT light.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace NRG\Framework\Controllers;

use NRG\Framework\Common\Registry as Registry;
use NRG\Framework\Exceptions\IllegalArgumentException as IllegalArgumentException;
use NRG\Database\Mappers as Mappers;

/**
 * Email controller
 *
 * @package NRG\Framework\Controllers
 */
class Email extends BaseController
{
    /**
     * XNAT object
     *
     * @var Xnat
     */
    protected $_xnat;

    /**
     * Pre-dispatch of action
     */
    public function preDispatch()
    {
	$this->_xnat = Registry::get("xnat");
    }

    /**
     * Compose email
     *
     * @protected: admin-only
     */
    public function composeAction()
    {
	$this->adminOnly();
    }

    /**
     * Send email
     *
     * @protected: admin-only
     */
    public function sendAction()
    {
	$this->adminOnly();

	$to = array();

	// get To: recipients
	if($this->_session->hasRequestParam("to"))
	{
	    $to = trim($this->_session->getRequestParam("to", false));

	    if($to == "")
	    {
		$this->_view->error = true;
		$this->_view->message = "recipient cannot be empty";

		return;
	    }
	    else if(strtolower($to) == "all")
	    {
		$mapper = new Mappers\User();
		$to = $mapper->getAllEmailAddrs();

		if(sizeof($to) == 0)
		{
		    $this->_view->error = true;
		    $this->_view->message = "no email addresses found";

		    return;
		}

		$to = implode(",", $to);
	    }
	}
	else
	{
	    $this->_view->error = true;
	    $this->_view->message = "no recipients provided";

	    return;
	}

	// get Subject:
	if(! $this->_session->hasRequestParam("subject"))
	    $subject = "";
	else
	    $subject = $this->_session->getRequestParam("subject");


	// get Message:
	if(! $this->_session->hasRequestParam("body"))
	    $body = "";
	else
	    $body = $this->_session->getRequestParam("body");

	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	$headers .= 'From: ' . $this->_xnat->getUser()->getEmail() . "\r\n";

	$this->_view->headers = $headers;
	$this->_view->to = $to;
	$this->_view->from = $this->_xnat->getUser()->getEmail();
	$this->_view->subject = $subject;
	$this->_view->body = $body;
    }
}
